#ifndef MY_KEY_H
#define MY_KEY_H
#include <Arduino.h>
#include <esp32-hal-adc.h>
#define KEY_IN_NUM  1
hw_timer_t * timer = NULL;
volatile SemaphoreHandle_t timerSemaphore;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
enum KEY_MODE
{
    NO_KEY=0,   //0
    K2_PRESS,   //1
    EC11_BTN,   //2
    EC11_LEFT,  //3
    EC11_RIGHT,  //4
    EC11_ROLL_END,//5
    EC11_ROLL_LEFT,//6
    EC11_ROLL_RIGHT,  //7
    EC11_BTN_IN,//8
    K2_PRESS_IN //9
};
volatile int Key_mode = NO_KEY;
static void key_process(void)
{
    static int analogVol;
    analogVol = analogReadMilliVolts(KEY_IN_NUM);
    //Serial0.println(analogVol);
    switch (analogVol)
  {
  case 1180 ... 1800:
    if(Key_mode==EC11_BTN_IN)
    {
        Key_mode = EC11_BTN;
    }
    else if( Key_mode==K2_PRESS_IN)
    {
        Key_mode = K2_PRESS ;
    }
    else
    {
        Key_mode = NO_KEY;
    }
    break;
  case 1140 ... 1160:
    Key_mode = EC11_ROLL_RIGHT;
    break;
  case 1090 ... 1110:
    Key_mode =EC11_ROLL_LEFT;
    break;
  case 1040 ... 1060:
    if(Key_mode==EC11_ROLL_LEFT)
    {
        Key_mode = EC11_LEFT;

    }
    else if(Key_mode ==EC11_ROLL_RIGHT)
    {
        Key_mode = EC11_RIGHT;
    }
    break;
  case 900 ... 1010:
    Key_mode = EC11_BTN_IN;
    break;
  case 200 ... 600:
    Key_mode =K2_PRESS_IN;
    break;
  default:
    Key_mode = NO_KEY;
    break;
  }


}
void ARDUINO_ISR_ATTR onTimer(){
  portENTER_CRITICAL_ISR(&timerMux);
  key_process();
  portEXIT_CRITICAL_ISR(&timerMux);
  xSemaphoreGiveFromISR(timerSemaphore, NULL);
}


void Adc_Key_init(void)
{
    analogReadResolution(12);
    pinMode(KEY_IN_NUM,INPUT);
    timerSemaphore = xSemaphoreCreateBinary();
    timer = timerBegin(0, 240, true);//timer div
    timerAttachInterrupt(timer, &onTimer, true);
    timerAlarmWrite(timer, 180, true);//  1000/x ms
    timerAlarmEnable(timer);

}

#endif